//
//  QYModifyInfoViewController.m
//  QingYue
//
//  Created by Zheng on 2017/5/23.
//  Copyright © 2017年 com.lanou.product_A. All rights reserved.
//

#import "QYModifyInfoViewController.h"
#import "QYModifyInfoNickNameViewController.h"

#import "QYModifyInfoCell.h"

#import "QYPhotoMaskChooseManager.h"

#import <AssetsLibrary/AssetsLibrary.h>

@interface QYModifyInfoViewController () <UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, copy) NSString *nickname;
@property (nonatomic) BOOL isUp;
@property (nonatomic, strong) UIImage *image;

@end

@implementation QYModifyInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"信息修改";
    
    _nickname = [kUserDefaults objectForKey:@"nickname"];
}

#pragma mark - TableView DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    QYModifyInfoCellStyle style = QYModifyInfoCellStyleHeadPortrait;
    if (indexPath.row == 1) {
        style = QYModifyInfoCellStyleNickname;
    } else if (indexPath.row == 2) {
        style = QYModifyInfoCellStyleReaderCard;
    }
    
    NSString *reuserIdentifier = [NSString stringWithFormat:@"QYModifyInfoCell_%lu",style];
    
    QYModifyInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:reuserIdentifier];
    if (!cell) {
        cell = [[QYModifyInfoCell alloc] initWithModifyInfoStyle:style reuseIdentifier:reuserIdentifier];
    }
    
    if (indexPath.row == 1) {
        cell.detailLbl.text = _nickname;
    }
    
    if (indexPath.row == 0) {
        
//        if (!_isUp) {
//            [cell.iconImgv sd_setImageWithURL:[NSURL URLWithString:_iconUrlStr] placeholderImage:[UIImage imageNamed:@"默认用户头像"]];
//
//        } else {
//            cell.iconImgv.image = _image;
//        }
        
        [cell.iconImgv sd_setImageWithURL:[NSURL URLWithString:_iconUrlStr] placeholderImage:[UIImage imageNamed:@"默认用户头像"]];

        
    }
    
    
    return cell;
}

- (void)setIconUrlStr:(NSString *)iconUrlStr {
    _iconUrlStr = iconUrlStr;
    
    [self.tableView reloadData];
}

- (void)actionWithType:(NSUInteger)type {
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    if (type == 0) {
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                sourceType = UIImagePickerControllerSourceTypeCamera;
        }
    } else {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self presentViewController:imagePickerController animated:YES completion:^{
        
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{

    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.2);
    NSString *imageBase = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
//        NSDictionary *param = @{@"UserName":[kUserDefaults objectForKey:@"username"],
//                                @"Imagebytes":imageBase};
        NSDictionary *param = @{@"UserName":[kUserDefaults objectForKey:@"username"],
                                @"ImageBytes":[NSString stringWithFormat:@"data:image/jpeg;base64,%@",imageBase]};
        
        
        [SVProgressHUD showWithStatus:@"正在上传"];
        
        [[YCRequestDataService sharedManager] Post:@"UpAvatar" parameters:param success:^(id response) {
            
            if ([response[@"Code"] isEqualToString:@"成功"]) {
                [SVProgressHUD showSuccessWithStatus:@"上传成功"];
                
//                _isUp = YES;
//                
//                _image = image;
                
                _iconUrlStr = response[@"Url"];
                
                [self.tableView reloadData];
            } else {
                [SVProgressHUD showErrorWithStatus:@"上传失败"];
            }
            
        } failure:^{
            [SVProgressHUD showErrorWithStatus:@"网络或服务器出错"];
        }];
        
    }];
    
    
}



#pragma mark - TableView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row == 0) {
#pragma mark 修改头像
        
        __block typeof(self) weakSelf = self;
        
        [[QYPhotoMaskChooseManager defaultManager] showPhotoMaskChooseView];
        
        [QYPhotoMaskChooseManager defaultManager].gotoPhotoLibBlock = ^{
            [weakSelf actionWithType:1];
        };
        
        [QYPhotoMaskChooseManager defaultManager].gotoPhotoTakeBlock = ^{
            [weakSelf actionWithType:0];
        };
        
    } else if (indexPath.row == 1) {
#pragma mark 修改昵称
        QYModifyInfoNickNameViewController *nickVC = [[QYModifyInfoNickNameViewController alloc] initWithStyle:UITableViewStyleGrouped];
        
        nickVC.nickBlock = ^(NSString *nickname) {
            _nickname = nickname;
            [self setNickNameWithRequest:_nickname];
            [self.tableView reloadData];
        };
        
        [self.navigationController pushViewController:nickVC animated:YES];
    }
}

- (void)setNickNameWithRequest:(NSString *)nick {
    NSDictionary *param = @{@"UserName":[kUserDefaults objectForKey:@"username"],
                            @"Name":nick};
    
    [[YCRequestDataService sharedManager] Post:@"ChangeName" parameters:param success:^(id response) {
        if ([response[@"Code"] isEqualToString:@"成功"]) {
            [kUserDefaults setObject:_nickname forKey:@"nickname"];
        }
        
    } failure:^{
        
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 72.5f;
    } else {
        return 50.f;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return .0001f;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
